package com.jilefojing.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.enums.ThirdPartyTypeEnum;
import com.jilefojing.beans.enums.foruser.StatusEnumForUser;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.User;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.dao.IUserDao;
import com.jilefojing.dao.base.impl.BaseDao;
import com.jilefojing.dao.mapper.IUserMapper;
import com.jilefojing.util.Detect;

/**
 * 
 * @author jgshun
 * 
 */
@Repository
public class UserDao extends BaseDao<User> implements IUserDao {

	@Autowired
	private IUserMapper userInfoMapper;

	@Override
	public User getUserByAccount(String account) throws UserContextException {
		Example example = new Example(User.class);
		Criteria exampleCriteria = example.createCriteria();
		StringBuilder orSub = new StringBuilder();
		orSub.append(User.COLUMN_EMAIL).append(" = ").append("'").append(account).append("'");// 邮箱
		orSub.append(" or ").append(User.COLUMN_TELPHONE).append(" = ").append("'").append(account).append("'");// 手机号
		orSub.append(" or ").append(User.COLUMN_NAME).append(" = ").append("'").append(account).append("'");// 用户名

		exampleCriteria.andCondition(orSub.toString());
		List<User> users = super.getListByExample(example);
		if (Detect.notEmpty(users)) {
			if (users.size() == 1) {
				return users.get(0);
			} else {
				throw new UserContextException(ResponseEnum.USER_REPEAT_ERRO);
			}
		}
		return null;
	}

	@Override
	public List<User> getByIds(List<Long> ids) {
		Example example = new Example(User.class);
		Criteria exampleCriteria = example.createCriteria();
		exampleCriteria.andIn(User.FIELD_ID, ids);
		return super.getListByExample(example);
	}

	@Override
	public Pagination<User> getPagination(List<StatusEnumForUser> statuses, Pagination<User> pagination) {
		Example example = new Example(User.class);
		Criteria criteria = example.createCriteria();
		if (Detect.notEmpty(statuses)) {
			List<Short> statusVals = new ArrayList<Short>();
			for (StatusEnumForUser _status : statuses) {
				statusVals.add(_status.getCode());
			}
			criteria.andIn(User.FIELD_STATUS, statusVals);
		}
		example.setOrderByClause(Detect.notEmpty(pagination.getOrders()) ? pagination.getOrdersToStr() : User.ORDER_CREATE_DATETIME_DESC);

		return super.getPagination(pagination, example);
	}

	@Override
	public User getUserByThirdParty(String thirdPartyId, ThirdPartyTypeEnum thirdPartyType) {
		// User record = new User();
		// record.setThirdpartyid(thirdPartyId);
		// record.setThirdpartytype((int) thirdPartyType.getValue());
		// return super.getOneByRecord(record);
		return null;
	}

}
